import * as faceapi from "face-api.js";

main()

async function main(){
    // 加载模型权重文件
    await faceapi.nets.ssdMobilenetv1.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceLandmark68Net.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceRecognitionNet.loadFromUri('http://127.0.0.1:8888/weights')

    await faceapi.loadFaceLandmarkModel('http://127.0.0.1:8888/weights')
    await faceapi.loadFaceRecognitionModel('http://127.0.0.1:8888/weights')
    await faceapi.nets.tinyFaceDetector.loadFromUri('http://127.0.0.1:8888/weights')

    const image1 = document.getElementById('image1')
    const image2 = document.getElementById('image2')

    const options = new faceapi.SsdMobilenetv1Options({ minConfidence:0.5 })
    const reference = await faceapi.detectAllFaces(image1, options).withFaceLandmarks().withFaceDescriptors()
    if (!reference.length) {
        return
    }

    
    const result = await faceapi.detectSingleFace(image2, options).withFaceLandmarks().withFaceDescriptor()
    if(!result){
        return
    }
    
    const faceMatcher = new faceapi.FaceMatcher(result)

    const canvas = document.getElementById('queryImgOverlay')
    faceapi.matchDimensions(canvas, image1)
    
    const resizedResults = faceapi.resizeResults(reference, image1)
    resizedResults.forEach(({ detection, descriptor }) => {
        const label = faceMatcher.findBestMatch(descriptor).toString()
        const options = { label }
        const drawBox = new faceapi.draw.DrawBox(detection.box, options)
        drawBox.draw(canvas)
    })
}